<?php

/*
路由模式
    路由模式和发布订阅模式类似，在基础上改变类型（fanout=>direct）,订阅模式是分发到所有绑定到交换机的队列，路由模式只分发到绑定交换机上面指定路由的队列


    php client.php warnning "这是warrnning数据"

    php server.php info
    php server.php warnning error
*/

require_once __DIR__ . '/../vendor/autoload.php';
 
use PhpAmqpLib\Connection\AMQPStreamConnection;
 
$exchange = 'routing'; // 交换器名称
 
try {
    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');// 建立连接到RabbitMQ服务器
    $channel = $connection->channel(); // 建立通道
    $channel->exchange_declare($exchange,"direct", false, false, false); // 试探性声明一个交换机
    list($queueName, ,) = $channel->queue_declare("", false, false, true, false); // 试探性声明一个队列
    $routingKeys = array_slice($argv, 1); // 获取routing_key
    if (empty($routingKeys)) throw new Exception('请输入至少一个routing_key'); // 输入routing_key
    foreach ($routingKeys as $routingKey) {
        $channel->queue_bind($queueName, $exchange, $routingKey); // 队列通过routing_key绑定交换机
    }
    echo " [*] Waiting for logs. To exit press CTRL+C\n";
    $callback = function ($msg) { // 回调函数
        sleep(3);
        // 手动确认消息是否正常消费，保证消息消费的幂等。
        $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
        echo ' [x] Received ', $msg->delivery_info['routing_key'], ':', $msg->body, "\n";
    };
    $channel->basic_consume($queueName, '', false, false, false, false, $callback); // 消费消息
    while(count($channel->callbacks)) {
        $channel->wait();
    }
    $channel->close(); // 通道关闭
    $connection->close(); // 连接关闭
} catch (Exception $e) {
    die($e->getMessage());
}